import { ref } from "vue";
import { checkCollision } from "./collision";
import { playerConfig } from "@/config/static";
import { useUserStore } from "@/store/userStore";
import {
  createCharacterAnimationController,
  CharacterAnimationController,
} from "./character";
import { Action, Direction } from "@/config/characterConfig";

const directionMap: Record<Direction, "up" | "down" | "left" | "right"> = {
  [Direction.Up]: "up",
  [Direction.Down]: "down",
  [Direction.Left]: "left",
  [Direction.Right]: "right",
};

/**
 * 键盘状态
 */
export const keys = ref({
  w: {
    pressed: false, // 用于判断是否按下
  },
  s: {
    pressed: false, // 用于判断是否按下
  },
  a: {
    pressed: false, // 用于判断是否按下
  },
  d: {
    pressed: false, // 用于判断是否按下
  },
});

export const playerSpeed = playerConfig.speed; // 角色移动速度
// 玩家控制器
export let playerController: CharacterAnimationController | null = null;
// 碰撞对象
export const collisionObjects = ref<
  Array<{ x: number; y: number; width: number; height: number }>
>([]);

// 添加时间相关变量，用于平滑移动
let lastTimestamp = 0;

/**
 * 初始化玩家控制器
 */
export const initPlayerController = async (
  spritesheetPath: string,
  canvas: any
): Promise<CharacterAnimationController | null> => {
  if (playerController) {
    console.log("玩家控制器已存在，跳过初始化");
    return playerController;
  }

  const ctx = canvas.getContext("2d");
  if (!ctx) {
    throw new Error("无法获取 2D 上下文");
  }
  console.log("创建新的玩家控制器实例");
  playerController = await createCharacterAnimationController(
    spritesheetPath,
    ctx
  );
  return playerController;
};

/**
 * 处理玩家移动
 */
export const handlePlayerMovement = (timestamp = 0) => {
  if (!playerController) return;

  const userStore = useUserStore();

  // 计算时间增量，用于平滑移动（改进计算方式）
  const deltaTime = Math.min((timestamp - lastTimestamp) / 16.67, 1);
  lastTimestamp = timestamp;

  let dx = 0;
  let dy = 0;
  let isMoving = false;
  let direction = userStore.playerPosition.direction.value || Direction.Down;

  if (keys.value.w.pressed) {
    dy -= playerSpeed;
    direction = Direction.Up;
    isMoving = true;
  }
  if (keys.value.s.pressed) {
    dy += playerSpeed;
    direction = Direction.Down;
    isMoving = true;
  }
  if (keys.value.a.pressed) {
    dx -= playerSpeed;
    direction = Direction.Left;
    isMoving = true;
  }
  if (keys.value.d.pressed) {
    dx += playerSpeed;
    direction = Direction.Right;
    isMoving = true;
  }

  // 设置动作（站立、行走或奔跑）
  let action = Action.Run;
  if (isMoving) {
    // action = playerSpeed > 3 ? Action.Run : Action.Walk;
    // 使用deltaTime使移动速度与帧率无关，保持平滑
    const speed = playerSpeed * deltaTime + 1;

    // 新的坐标
    const newX = userStore.playerPosition.x + dx * speed;
    const newY = userStore.playerPosition.y + dy * speed;

    // 检测碰撞
    if (!checkCollision(newX, newY, playerConfig.width, playerConfig.height)) {
      // 如果没有碰撞，更新角色位置
      userStore.playerPosition.x = newX;
      userStore.playerPosition.y = newY;

      userStore.updatePlayerPosition(newX, newY);
      userStore.updatePlayerDirection({
        name: directionMap[direction as Direction],
        value: direction,
      });
    }
  }

  // 设置角色动作和方向
  playerController.setAction(action, direction, isMoving);
};

/**
 * 键盘控制
 * @returns 销毁函数
 */
export const setupKeyboardControls = () => {
  const handleKeyDown = (e: KeyboardEvent) => {
    // 防止按键事件影响页面滚动
    if (["w", "s", "a", "d", "shift"].includes(e.key.toLowerCase())) {
      e.preventDefault();
    }

    const key = e.key.toLowerCase();
    if (key in keys.value) {
      keys.value[key as keyof typeof keys.value].pressed = true;
    }
  };

  const handleKeyUp = (e: KeyboardEvent) => {
    const key = e.key.toLowerCase();
    if (key in keys.value) {
      keys.value[key as keyof typeof keys.value].pressed = false;
    }
  };

  window.addEventListener("keydown", handleKeyDown);
  window.addEventListener("keyup", handleKeyUp);

  return () => {
    window.removeEventListener("keydown", handleKeyDown);
    window.removeEventListener("keyup", handleKeyUp);
  };
};
